<?php
/**
 * User: @lose
 * Date: 2020-04-01
 * Time: 17:28
 */

namespace Frieza\Modules\ImageCreate\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\pockets\export\ExportData;
use Biz\tools\FileUpload;
use Doraemon\model\ImageCreate\ImageCreate;
use Doraemon\model\ImageCreate\ImageCreateModule;
use Doraemon\model\ImageCreate\ImageCreateModuleAvatar;
use Doraemon\model\ImageCreate\ImageCreateModuleImg;
use Doraemon\model\ImageCreate\ImageCreateModuleQr;
use Doraemon\model\ImageCreate\ImageCreateModuleText;
use Doraemon\model\ImageCreate\ImageCreateModuleZip;
use Doraemon\model\ImageCreate\ImageUploadHistory;
use Doraemon\service\ImageCreate\Schedule;
use Doraemon\tools\Curl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use GuzzleHttp\RequestOptions;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\ImageCreate\Schedule as sISchedule;
use Doraemon\model\ImageCreate\ImageCreate as mImageCreate;


class IndexController extends Controller
{
    public function index(Content $content, Request $request)
    {
        $where = $this->buildWhere($request->all());
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $limit = [($page - 1) * $pageSize, $pageSize];

        $list = sISchedule::getList($where, $limit);

        return $content
                    ->header('模板列表')
                    ->breadcrumb(['text' => '模板列表'])
                    ->row($this->_formatGrid($list, $page, $pageSize, $where));
    }

    // 具体模板列表内容排布
    public function _formatGrid($list, $page, $pageSize, $where)
    {
        $options = array(
            "currentPage" => $page,
            "perPage" => $pageSize,
        );

        $gridModel = new pGridDataModel($list['list'], $list['total'], $options);

        $grid = Admin::grid($gridModel,
            function (Grid $grid)use($pageSize, $where) {
                Admin::script($this->onlineScript());

                $grid->paginate($pageSize);
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('title', '标题')->placeholder('输入标题关键字');
                        $filter->equal('admin_id', '创建者')->select(Admin::user()->pluck('name', 'id')->toarray());
                        $filter->equal('i_status', '模板状态')->select(ImageCreate::ALL_STATUS)->default(ImageCreate::STATUS_PUBLISH);
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('start_time', '开始时间')->datetime();
                        $filter->equal('end_time', '结束时间')->datetime();
                    });
                });

                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column('id', 'id');

                $grid->column('title', '标题');

                $grid->column('addtime', '添加时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });

                $grid->column('zip_url', '生成的zip url地址');

                $grid->column('i_status', '状态')->display(function () {
                    return mImageCreate::ALL_STATUS[$this->i_status];
                });

                $grid->column('admin_id', '创建者')->display(function () {
                    return Admin::user()->find($this->admin_id)->name;
                });

                if ($where["i_status"] == ImageCreate::STATUS_DELETE) {
                    $grid->actions(function (Grid\Displayers\Actions $actions) {
                        $actions->disableDelete();
                        $actions->disableEdit();

                        $actions->append('&nbsp;<a class="fa online-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">恢复正常</a>');
                    });
                } else {
                    $grid->actions(function (Grid\Displayers\Actions $actions) {
                        $actions->disableEdit();
                        $actions->prepend('&nbsp;<a href="/admin/ImageCreate/'.$actions->row->id.'/edit/'.Schedule::TEMPLATE_CONFIGURE_TAB_BASIC.'" class="grid-row-edit"><i class="fa fa-edit"></i></a>');
                    });
                }
            }
        );
        return $grid;
    }

    // 下载图片生成的url列表 csv 文件
    public static function downloadUrlList($id, $imageCreateId)
    {
        $imageUploadHistoryData = ImageUploadHistory::getDataById($id);

        $csv_data = FileUpload::getFile($imageUploadHistoryData["pic_url_list_file"]);
        $csv_data = mb_convert_encoding($csv_data, "cp936", "UTF-8");

        $fileName = Schedule::getPrefixName($imageCreateId, $imageUploadHistoryData);
        $fileName .= ".csv";

        header("Content-type:text/csv;");
        header("Content-Disposition:attachment;filename=" . $fileName);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $csv_data;
    }

    // 下载图片生成的压缩包文件
    public static function downloadZipImg($id, $imageCreateId)
    {
        $imageUploadHistoryData = ImageUploadHistory::getDataById($id);

        $zipData = FileUpload::getFile($imageUploadHistoryData["pic_list_zip"]);

        $uniqueName = md5(time().rand(0, 10000));
        $zipTmpFilePath = "/tmp/{$uniqueName}.zip";
        file_put_contents($zipTmpFilePath, $zipData);

        $fp=fopen($zipTmpFilePath,"r");
        $file_size=filesize($zipTmpFilePath);//获取文件的字节

        $zipName = Schedule::getPrefixName($imageCreateId, $imageUploadHistoryData);
        $zipName .= ".zip";

        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:".$file_size);
        Header("Content-Disposition: attachment; filename={$zipName}");
        $buffer=1024; //设置一次读取的字节数，每读取一次，就输出数据（即返回给浏览器）
        $file_count=0; //读取的总字节数

        //向浏览器返回数据 如果下载完成就停止输出，如果未下载完成就一直在输出。根据文件的字节大小判断是否下载完成
        while(!feof($fp) && $file_count<$file_size){
            $file_con=fread($fp,$buffer);
            $file_count+=$buffer;
            echo $file_con;
        }
        fclose($fp);
        //下载完成后删除压缩包，临时文件夹
        if($file_count >= $file_size) {
             unlink($zipTmpFilePath);
        }
    }

    // 模板删除
    public function deleteTemplate(Request $request, $id)
    {
        $rs = $this->authControl($id);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '权限不够，只有创建者有权限编辑'
            ]);
            return back()->with(compact('error'))->withInput();
        }

        $updateData = array(
            "i_status" => ImageCreate::STATUS_DELETE,
        );

        $rs = ImageCreate::saveInfo($id, $updateData);

        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        }

        return response()->json([
            'status' => false,
            'message' => "删除失败",
        ]);
    }

    // 模板恢复
    public function onlineTemplate(Request $request)
    {
        $id = $request->input('id', 0);

        $rs = $this->authControl($id);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '权限不够，只有创建者有权限编辑'
            ]);
            return back()->with(compact('error'))->withInput();
        }

        $updateData = array(
            "i_status" => ImageCreate::STATUS_PUBLISH,
        );

        $rs = ImageCreate::saveInfo($id, $updateData);

        if ($rs) {
            $respond = [
                'title' => '模板 ID: ' . $id . ' 恢复成功',
                'code' => 1
            ];
        } else {
            $respond = [
                'title' => '模板 ID: ' . $id . ' 恢复失败，请重试',
                'code' => 1
            ];
        }

        return response()->json($respond);
    }

    /** 保存模板基本信息
     * @param Request $request
     */
    public function saveBasicInfo(Request $request)
    {
        $id = $request->input('id', 0);

        if ($id) {
            $rs = $this->authControl($id);
            if (!$rs) {
                $error = new MessageBag([
                    'title' => '权限不够，只有创建者有权限编辑'
                ]);
                return back()->with(compact('error'))->withInput();
            }
        }

        $data = [
            'title' => $request->input('title', ''),
            'drawing_board_width' => $request->input('drawing_board_width', 0),
            'drawing_board_height' => $request->input('drawing_board_height', 0),
            'background_color' => $request->input('background_color', ''),
            'i_status' => mImageCreate::STATUS_PUBLISH,
        ];

        $imageId = Schedule::saveTemplateBasicData($id, $data);

        if($imageId) {
            return redirect(url("/admin/ImageCreate/{$imageId}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_BASIC));
        } else {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput(array(
                "tab_type" => Schedule::TEMPLATE_CONFIGURE_TAB_BASIC
            ));
        }
    }

    // 构建查询条件
    private function buildWhere($params)
    {
        $where = [];

        if (isset($params["i_status"]) && $params["i_status"]) {
            $where['i_status'] = $params["i_status"];
        } else {
            $params["i_status"] = ImageCreate::STATUS_NORMAL;
            $where['i_status'] = $params["i_status"];
        }

        if($params['title']) {
            $where['title[~]'] = $params['title'];
        }

        if($params['admin_id']) {
            $where['admin_id'] = $params['admin_id'];
        }

        if($params['start_time']) {
            $where['addtime[>=]'] = strtotime($params['start_time']);
        }

        if($params['end_time']) {
            $where['addtime[<=]'] = strtotime($params['end_time']);
        }

        return $where;
    }

    // 模板信息修改
    public function pageEdit(Content $content, Request $request, $id = 0, $tabType = 0)
    {
        $where = $request->all();
        $sessionData = session('_old_input');
        $sessionTabType = isset($sessionData["tab_type"]) && $sessionData["tab_type"] ? $sessionData["tab_type"] : 0;
        if ($sessionTabType) {
            $tabType = $sessionTabType;
        }

        if (!$tabType) {
            $tabType = Schedule::TEMPLATE_CONFIGURE_TAB_BASIC;
        }

        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);

        $tab = new Tab();
        //基础信息
        $baseInfoForm = $this->_getPageBaseInfoForm($id);

        if ($tabType == Schedule::TEMPLATE_CONFIGURE_TAB_BASIC) {
            $tab->add('基础信息', $baseInfoForm, true);
        } else {
            $tab->addLink('基础信息', "/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_BASIC);
        }

        if ($id) {
            if ($tabType == Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST) {
                $detailGrid = $this->_getPageModuleGrid($id, $page, $pageSize);
                $tab->add('模块列表',  $detailGrid->render(), true);
            } else {
                $tab->addLink('模块列表',  "/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST);
            }

            // 上传文件生成图片
            if ($tabType == Schedule::TEMPLATE_CONFIGURE_TAB_FORM) {
                $imageCreateData = ImageCreate::getDataById($id);
                $imageCreateData["tab_type"] = Schedule::TEMPLATE_CONFIGURE_TAB_FORM;

                $page = $request->input('page', 1);
                $pageSize = $request->input('per_page', 10);

                $limit = [($page - 1) * $pageSize, $pageSize];
                $uploadFileGrid = $this->_getImgCreateForm($id, $imageCreateData, $limit, $page, $pageSize, $where);

                $tab->add('提交生成任务',  $uploadFileGrid, true);
            } else {
                $tab->addLink('提交生成任务',  "/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_FORM);
            }
        }

        $content->header('模板配置')
            ->breadcrumb([
                'text' => '模板列表',
                'url' => '/ImageCreate'
            ], ['text' => '模板配置'])
            ->row($tab);
        return $content;
    }

    // 下载模板
    public function downloadTemplate($id)
    {
        $imageCreateInfo = ImageCreate::getDataById($id);

        $sortedModuleInfos = Schedule::getSortModuleInfos($id);
        $fieldData = array();

        foreach ($sortedModuleInfos as $item) {
            array_push($fieldData, $item["title"]);
        }
        $csv_data  = implode(",", $fieldData);

        $csv_data = mb_convert_encoding($csv_data, "cp936", "UTF-8");
        $file_name = $imageCreateInfo["title"].'.csv';
        header("Content-type:text/csv;");
        header("Content-Disposition:attachment;filename=" . $file_name);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $csv_data;
    }

    // 获取上传文件生成图片
    private function _getImgCreateForm($id, $formInfo, $limit, $page, $pageSize, $where)
    {
        $form = new Form($formInfo);

        $form->text('pic_url_file',"展示上传的文件")->placeholder("用于展示上传的文件")->disable();
        $form->fileUpload("pic_url_file", '用于批量生成图片的文件', ['drop_zone_enabled' => false, 'allowed_file_extensions' => ["csv"], 'showPreview' => false])->help('请下载模板进行填写，填写完成之后上传');
        $form->hidden('pic_url_file');

        $form->hidden('tab_type');
        $form->radio('is_pack', '是否开启打包功能')->options(Schedule::IS_PACK)->default(Schedule::IS_PACK_OFF)
            ->help(" 1. 不开启打包，将会生成一个csv文件，里面保存生成的图片地址<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 2.开启打包，不但会生成图片地址，还会对生成的图片文件，打包成一个压缩包，用于下载,比较耗时");

        $form->action("/admin/ImageCreate/imageId/{$id}/uploadFileToCreate");
        $form->html('<div class="btn-group pull-left">
                <a  class="btn btn-info pull-right" href="/admin/ImageCreate/'.$id.'/download/template" target="_blank">模板下载</a>
            </div>');
        $form->disableReset();

        $uploadHistory = $this->_formatUploadHistoryGrid($id, $limit, $page, $pageSize, $where);
        return $form->render().$uploadHistory->render();
    }

    public function _formatUploadHistoryGrid($id, $limit, $page, $pageSize, $where)
    {
        $imageUploadHistorys = Schedule::getHistoryList($id, $limit, $where);
        $gridModel = new pGridDataModel($imageUploadHistorys['list'], $imageUploadHistorys['total'], array(
            "currentPage" => $page,
            "perPage" => $pageSize,
        ));

        $grid = Admin::grid($gridModel,
            function (Grid $grid) use($pageSize, $id) {
                $grid->paginate($pageSize);
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
//                        $filter->equal('title', '标题')->placeholder('输入标题关键字');
                        $filter->equal('admin_id', '创建者')->select(Admin::user()->pluck('name', 'id')->toarray());
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('start_time', '开始时间')->datetime();
                        $filter->equal('end_time', '结束时间')->datetime();
                    });
                });

                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->column('id', "任务id");

                $grid->column('operate', '操作人')->display(function (){
                    return Admin::user()->find($this->admin_id)->name;
                });

                $grid->column('addtime', '操作时间')->display(function (){
                    return date("Y-m-d H:i:s", $this->addtime);
                });

                $grid->column('is_pack', '是否打包')->display(function (){
                    if($this->is_pack) {
                        return "打包";
                    } else {
                        return "不打包";
                    }
                });

                $grid->column('pic_url_list_file', '生成的图片地址')->display(function ()use($id){
                    if ($this->pic_url_list_file) {
                        if ($this->addtime + 86400 * 15 -  time() < 0) {
                            return "链接已失效，请重新添加任务";
                        }

                        $csvFileName = Schedule::getPrefixName($id, array(
                            "addtime" => $this->addtime,
                            "admin_id" => $this->admin_id
                        ));
                        return '<a class="fa fa-download" href="'.Schedule::EXPORT_URL."/".$this->pic_url_list_file.'" target="_blank">'.$csvFileName.'.csv</a>';
                    }
                });

                $grid->column('pic_list_zip', '生成的图片压缩包地址')->display(function ()use($id){
                    if ($this->pic_list_zip) {
                        if ($this->addtime + 86400 * 15 -  time() < 0) {
                            return "链接已失效，请重新添加任务";
                        }

                        $zipFileName = Schedule::getPrefixName($id, array(
                            "addtime" => $this->addtime,
                            "admin_id" => $this->admin_id
                        ));

                        return '<a class="fa fa-download" href="'.Schedule::EXPORT_URL."/".$this->pic_list_zip.'" target="_blank">'.$zipFileName.'.zip</a>';
                    }
                });

                $grid->column('i_status', '任务状态')->display(function (){
                    return  Schedule::TASK_STATUS[$this->i_status];
                });

                $grid->column('userful_time', '链接有效时间')->display(function (){
                    if ($this->i_status == ImageUploadHistory::STATUS_NORMAL) {
                        $leaveTime = $this->addtime + 86400 * 15 -  time();
                        $day = intval($leaveTime / 86400);
                        $hour = intval(($leaveTime % 86400) / 3600);
                        $minute = intval((($leaveTime % 86400) % 3600) / 60);

                        if ($day < 0 || $hour < 0 || $minute  < 0) {
                            return "链接已失效，请重新添加任务";
                        } else {
                            return "还剩 {$day}天，{$hour}小时， {$minute}分钟";
                        }
                    }

                    return "";
                });
            }
        );
        return $grid;
    }

    // 上传文件进行图片生成
    public function uploadFileToCreate(Request $request, $id)
    {
        ini_set('memory_limit', '100M');
        $isOnline = strpos($_SERVER["HTTP_REFERER"],"haohaozhu.me") != false ? true : false;

        $adminEmail = Admin::user()->email;
        if (!$adminEmail) {
            $error = new MessageBag([
                'title' => '请设置管理员Email'
            ]);

            return back()->with(compact('error'))->withInput(array(
                "tab_type" => Schedule::TEMPLATE_CONFIGURE_TAB_FORM
            ));
        }

        $allData = $request->all();
        $file = $allData["pic_url_file"];
        $contents = FileUpload::getFile($file);

        if (empty($contents)) {
            $error = new MessageBag([
                'title' => '文件数据为空'
            ]);

            return back()->with(compact('error'))->withInput(array(
                "tab_type" => Schedule::TEMPLATE_CONFIGURE_TAB_FORM
            ));
        }

        $imageCreateBasicInfo = ImageCreate::getDataById($id);
        if (!(is_array($imageCreateBasicInfo) && $imageCreateBasicInfo)) {
            $error = new MessageBag([
                'title' => "模板 {$id} 数据不存在"
            ]);
            return back()->with(compact('error'))->withInput(
                array(
                    "tab_type" => Schedule::TEMPLATE_CONFIGURE_TAB_FORM
                )
            );
        }

        // 验证文件中数据的列数和模板中设置的组件数个数相同
        $templateModuleSort = Schedule::getSortModuleInfos($id);

        // zip命名模块存在的位置
        $isZipIndex = null;
        foreach ($templateModuleSort as $key => $templateModuleItem) {
            if (isset($templateModuleItem[Schedule::MODULE_TYPE]) &&  $templateModuleItem[Schedule::MODULE_TYPE] == Schedule::MODULE_TYPE_ZIP_NAME) {
                $isZipIndex = $key;
            }
        }

        // 验证模块数量和用户填写的信息列数是否一致 和 验证名字的准确性
        $templateModuleCount = count($templateModuleSort);

        $unMatchDataRow = [];
        $nameUnLegalDataRow = [];

        $contentArr = Schedule::getCsvData($file, $contents);

        foreach ($contentArr as $row => $itemArr) {
            $columnNum = count($itemArr);

            if ($columnNum != $templateModuleCount) {
                array_push($unMatchDataRow, $row + 1);
                continue;
            }

            // 验证名字的准确性
            if ($isZipIndex !== null) {
                $rs = Schedule::isFileNameLegal($itemArr[$isZipIndex]);
                if (!$rs) {
                    array_push($nameUnLegalDataRow, $row + 1);
                }
            }
        }

        if (is_array($unMatchDataRow) && $unMatchDataRow) {
            $strMess = implode(",",$unMatchDataRow);

            $error = new MessageBag([
                'title' => $strMess."，文件中这几行的数据列数和模板组件数不统一，请检查"
            ]);
            return back()->with(compact('error'))->withInput(
                array(
                    "tab_type" => Schedule::TEMPLATE_CONFIGURE_TAB_FORM
                )
            );
        }

        if (is_array($nameUnLegalDataRow) && $nameUnLegalDataRow) {
            $strMess = implode(",",$nameUnLegalDataRow);

            $error = new MessageBag([
                'title' => $strMess."，文件中这几行的数据命名不规范，名字中不能带 ".Schedule::UNLEGAL_CHAR
            ]);
            return back()->with(compact('error'))->withInput(
                array(
                    "tab_type" => Schedule::TEMPLATE_CONFIGURE_TAB_FORM
                )
            );
        }

        $currentTime = time();
        // 先在上传历史表里插一条记录
        $adminId = Admin::user()->id;
        $addUploadHistoryData = array(
            "admin_id" => $adminId,
            "is_pack" => $allData["is_pack"],
            "addtime" => $currentTime,
            "image_create_id" => $id,
            "i_status" => ImageUploadHistory::STATUS_PROCESS
        );

        $uploadHistoryId = ImageUploadHistory::addInfo($addUploadHistoryData);
        if (!$uploadHistoryId) {
            $error = new MessageBag([
                'title' => "添加生成任务失败，请重试"
            ]);
            return back()->with(compact('error'))->withInput(
                array(
                    "tab_type" => Schedule::TEMPLATE_CONFIGURE_TAB_FORM
                )
            );
        }

        $params = [
            "id" => $id,
            "fileName" => $file,
            "upload_history_id" => $uploadHistoryId,
            "is_pack" => $allData["is_pack"],
            "admin_email" => $adminEmail,
            "current_time" => $currentTime,
            "is_zip_index" => $isZipIndex,
            "operate_name" => Admin::user()->find($adminId)->name,
            "is_online" => $isOnline
        ];

        // 调用异步生成任务
        if ($isOnline) {
            ExportData::addTask([Schedule::class, 'BatchCreateByFile'], compact('params'));
        } else {
            $args = array(
                "params" => array("params" => $params),
                "callback" => [Schedule::class, 'BatchCreateByFile']
            );
            ExportData::runTask($args);
        }

        $success = new MessageBag([
            'title' => '提交成功'
        ]);

        return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_FORM))->with(compact('success'));
    }

    private function _getPageBaseInfoForm($id = 0)
    {
        $info = [];
        if ($id) {
            $info = Schedule::getBasicInfoById($id);
        }
        $info["tab_type"] = Schedule::TEMPLATE_CONFIGURE_TAB_BASIC;

        $baseInfoForm = new Form($info);
        $baseInfoForm->hidden('id' ,'内容id');
        $baseInfoForm->hidden('tab_type', 'tab_type');
        $baseInfoForm->text('title', '标题')->placeholder('请输入标题，不超过50个字')->help("用于标记这个模板的用途")->required();

        $baseInfoForm->number('drawing_board_width','画板宽度')->required()->help('最后生成图片的宽度');
        $baseInfoForm->number('drawing_board_height','画板高度')->required()->help('最后生成图片的高度');
        $baseInfoForm->color('background_color','画板颜色')->default("#000000")->required()->help('整个图片的背景色');
        $baseInfoForm->action('/admin/ImageCreate/saveBasicInfo');
        return $baseInfoForm;
    }

    // 预览
    public static function preview($id)
    {
        ini_set('memory_limit', '200M');
        $imageIds = array();
        $avatarIds = array();
        $qrIds = array();
        $textIds = array();
        $zipIds = array();

        // 获取排序后的模块数据
        $templateModuleSort = Schedule::getSortModuleInfos($id, $imageIds, $avatarIds, $qrIds, $textIds, $zipIds);

        // 获取hash 具体模块信息
        list($hashImageModuleList, $hashAvatarModuleList, $hashQrModuleList, $hashTextModuleList, $hashZipModuleList) = Schedule::getHashModuleInfos($id, $imageIds, $avatarIds, $qrIds, $textIds, $zipIds);

        // 将模板信息 和 模块信息 进行关联
        $templateData = Schedule::getTemplateRelatedModuleData($templateModuleSort, $hashImageModuleList, $hashAvatarModuleList, $hashQrModuleList, $hashTextModuleList, $hashZipModuleList);

        // 构造数据格式
        $imageCreateData = ImageCreate::getDataById($id);

        // 构造图片生成参数
        $buildParams = Schedule::buildImageCreateParams($imageCreateData, $templateData, array(),true);

        Curl::$defaultConfig[RequestOptions::TIMEOUT] = 100;

        $imgHandleUrl = Schedule::getImgUrl();
        $rs = Curl::Request("POST", $imgHandleUrl.Schedule::IMAGE_CREATE_PREVIEW_URL, ['form_params' => [
            "params" => json_encode($buildParams),
            "file_name" => md5(time()).rand(0, 10000).".jpg"
        ]]);

        $data = json_decode($rs['data'], true);

        $url = \Doraemon\tools\ImgUrl::getUrl(\Doraemon\tools\ImgUrl::APPTYPE_OP, $data["data"]["id"], \Doraemon\tools\ImgUrl::IMAGE_SIZE_SQ_BEST_PHONE);
        self::showImg($url);
    }

    // 图片在浏览器上展示
    public static function showImg($img){
        $info = getimagesize($img);
        $imgExt = image_type_to_extension($info[2], false); //获取文件后缀
        $fun = "imagecreatefrom{$imgExt}";
        $imgInfo = $fun($img);         //1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename )
        $mime = image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型
        header('Content-Type:'.$mime);
        $quality = 100;
        if($imgExt == 'png') $quality = 9;   //输出质量,JPEG格式(0-100),PNG格式(0-9)
        $getImgInfo = "image{$imgExt}";
        $getImgInfo($imgInfo, null, $quality); //2.将图像输出到浏览器或文件。如: imagepng ( resource $image )
        imagedestroy($imgInfo);
    }

    /**
     * @desc 模块列表
     * @param $pageId
     * @return Grid
     */
    private function _getPageModuleGrid($id, $page, $pageSize)
    {
        $limit = [($page - 1) * $pageSize, $pageSize];
        $moduleList = Schedule::getModuleList($id, $limit);

        $options = array(
            "currentPage" => $page,
            "perPage" => $pageSize,
        );

        $gridModel = new pGridDataModel($moduleList['list'], $moduleList['total'], $options);

        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) use ($id,$gridModel ) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();

                //添加按钮
                $grid->tools(function (Grid\Tools $tool) use ($id, $grid) {
                    $tool->append(self::_getPageModuleTools($grid));
                    $tool->append('<a class="btn btn-sm btn-success preview" href="/admin/ImageCreate/'.$id.'/preview" target="_blank">
        <i class="fa fa-hand-o-right"></i>&nbsp;预览
    </a>&nbsp;&nbsp;');
                });

                $grid->column('id')->sort();

                $grid->column('title', '模块名称');

                $grid->column('module_type', '模块类型')->display(function () {
                    return Schedule::MODULE_TYPE_LIST[$this->module_type];
                });

                $grid->column('addtime', '添加时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) use($id) {
                    $actions->disableEdit();
//                    $actions->disableDelete();
                    $actions->prepend('<a class="grid-row-edit"  href="'."edit/{$actions->row["id"]}/edit/{$actions->row["module_type"]}/type".'"><i class="fa fa-edit"></i></a>');
//                    $actions->append('<a href="javascript:void(0);" data-module="'.$actions->row["id"].'" data-id="'.$id.'"  class="offline-data grid-row-delete"><i class="fa fa-trash"></i></a>');

                });
            });
        return $detailGrid;
    }

    private function reloadScript()
    {
        return <<<SCRIPT
        $('.reloadJoin').unbind('click').click(function(){
            var id = $(this).data('id');
            let url = id  + '/reload'
            let params = {}
            toastr.success('更新任务已经添加,稍后查看');
            $.post(url, params);
        });
SCRIPT;
    }

    /**
     * @param $grid Grid
     * @return string
     */
    private static function _getPageModuleTools($grid)
    {
        // 可以添加的模块信息
        $toolsConfig = Schedule::MODULE_CONFIG;

        $tools = '';
        foreach ($toolsConfig as $v) {
            switch ($v['type']) {
                case Schedule::MODULE_TYPE_IMG:
                    $href = $grid->resource() . '/add/' . $v['type'];
                    $tools .= "<li><a href='$href'>". Schedule::MODULE_TYPE_LIST[$v['type']] ."</a></li>";
                    break;
                case Schedule::MODULE_TYPE_AVATAR:
                case Schedule::MODULE_TYPE_QR:
                case Schedule::MODULE_TYPE_TEXT:
                case Schedule::MODULE_TYPE_ZIP_NAME:
                    $href = $grid->resource() . '/add/' . $v['type'];
                    $tools .= '<li role="separator" class="divider"></li>';
                    $tools .= "<li><a href='$href'>". Schedule::MODULE_TYPE_LIST[$v['type']] ."</a></li>";
                    break;
            }
        }

        return <<<TOOLS
<div class="btn-group pull-right" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="添加"><i class="fa fa-plus"></i><span class="hidden-xs"> 添加</span></a>
    <button type="button" class="btn btn-sm btn-twitter dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
        <span class="caret"></span>
        <span class="sr-only">Toggle Dropdown</span>
    </button>
    <ul id="menu3" class="dropdown-menu" aria-labelledby="drop6">
      $tools
    </ul>
</div>
TOOLS;
    }

    /**
     * 添加模块
     * @param Content $content
     * @param $id int 活动页id
     * @param $type int 模块id
     * @return Content
     */
    public function moduleAdd(Content $content, $id, $tabType, $type)
    {
        $tab = new Tab();
        $tab->add('模块基础信息', $this->_getModuleForm($id, null, 0, $type));
        return $content
            ->header('添加' . Schedule::MODULE_TYPE_LIST[$type])
            ->breadcrumb(
                [
                    'text' => '模板列表',
                    'url' => '/ImageCreate'
                ],
                [
                    'text' => '模板配置页',
                    'url' => '/ImageCreate/' . $id . '/edit/'.Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST
                ],
                ['text' => '添加' . Schedule::MODULE_TYPE_LIST[$type]]
            )
            ->row($tab);
    }

    /**
     * 模块修改
     * @param Content $content
     * @param $id int 活动页id
     * @param $type int 模块id
     * @return Content
     */
    public function moduleEdit(Content $content, $id, $moduleId, $moduleType)
    {
        $tab = new Tab();
        $moduleInfo = ImageCreateModule::getDataById($moduleId);
        if (empty($moduleInfo)) {
            $error = new MessageBag([
                'title' => '数据不存在，请重试'
            ]);
            return back()->with(compact('error'));
        }

        $formInfo = null;
        switch ($moduleInfo["module_type"]) {
            case Schedule::MODULE_TYPE_IMG:
                $formInfo = ImageCreateModuleImg::getDataById($moduleInfo["module_obj_id"]);
                break;
            case Schedule::MODULE_TYPE_AVATAR:
                $formInfo = ImageCreateModuleAvatar::getDataById($moduleInfo["module_obj_id"]);
                break;
            case Schedule::MODULE_TYPE_QR:
                $formInfo = ImageCreateModuleQr::getDataById($moduleInfo["module_obj_id"]);
                break;
            case Schedule::MODULE_TYPE_TEXT:
                $formInfo = ImageCreateModuleText::getDataById($moduleInfo["module_obj_id"]);
                break;
            case Schedule::MODULE_TYPE_ZIP_NAME:
                $formInfo = ImageCreateModuleZip::getDataById($moduleInfo["module_obj_id"]);
                break;
        }

        if (!(is_array($formInfo) && $formInfo)) {
            $error = new MessageBag([
                'title' => '数据不存在，请重试'
            ]);
            return back()->with(compact('error'));
        }

        // 添加标题信息
        $formInfo["title"] = isset($moduleInfo["title"]) && $moduleInfo["title"] ? $moduleInfo["title"] : "";

        $tab->add('模块基础信息', $this->_getModuleForm($id, $formInfo, $moduleId, $moduleType));
        return $content
            ->header('修改' . Schedule::MODULE_TYPE_LIST[$moduleType])
            ->breadcrumb(
                [
                    'text' => '模板列表',
                    'url' => '/ImageCreate'
                ],
                [
                    'text' => '模板配置页',
                    'url' => '/ImageCreate/' . $id . '/edit/'.Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST
                ],
                ['text' => '模块修改' . Schedule::MODULE_TYPE_LIST[$moduleType]]
            )
            ->row($tab);
    }

    // 模块删除
    public  function deleteModuleInfo($id, $tabId, $moduleId)
    {
        $rs = $this->authControl($id);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '权限不够，只有创建者有权限编辑'
            ]);
            return back()->with(compact('error'))->withInput();
        }

        $updateData = array(
            "i_status" => ImageCreateModule::STATUS_DELETE
        );

        $rs = ImageCreateModule::saveInfo($moduleId, $updateData);

        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        }

        return response()->json([
            'status' => false,
            'message' => "删除失败",
        ]);
    }

    /**
     * 活动页添加模块
     * @param $pageId
     * @param $moduleInfo
     * @param int $moduleType
     * @return Form
     */
    private function _getModuleForm($id, $formInfo, $moduleId, $moduleType = 1)
    {
        $form = new Form($formInfo);

        switch ($moduleType) {
            case Schedule::MODULE_TYPE_IMG :
                $form->hidden('id','图片模块id');
                $form->text('title','标题')->required()->default("")->help('请输入该模块的名称，用于标记这个模块是什么信息，会出现在模板文件里');

                $form->radio('is_need_round', '是否变圆')->options(Schedule::IS_NEED_ROUND)->default(Schedule::IS_NEED_ROUND_OFF)
                    ->help("开启后，图片会变成正圆。圆的直径以图片宽度为准。");


                $form->radio('align_type', '对齐方式')->options(Schedule::IMG_ALIGN_TYPE)->default(Schedule::IMG_ALIGN_TYPE_TOP)
                    ->help("文本的x轴计算方式<br/>1.默认：和其他模块计算方式一样，以模块的左边开始计算。<br/>2.居中：图片在x轴方向将居于整个画板的中间位置")
                    ->when(Schedule::IMG_ALIGN_TYPE_TOP, function(Form $form) {
                        $form->number('x','x轴位置')->required()->default(0)->help('图片展示在画板的X轴位置，坐标原点在画板左上角');
                    });

                $form->number('y','y轴位置')->required()->default(0)->help('图片展示在画板的Y轴位置，坐标原点在画板左上角');

                $form->number('width','图片的宽度')->required()->default(0)->help('图片的宽度');
                $form->number('height','图片的高度')->required()->default(0)->help('图片的高度');

                $form->text('fake_url','用于预览的图片url')->default("")->help('用于预览的图片url，不填的话使用默认图片');
                break;

            case Schedule::MODULE_TYPE_AVATAR:
                $form->hidden('id','头像模块id');
                $form->text('title','标题')->required()->default("")->help('请输入该模块的名称，用于标记这个模块是什么信息，会出现在模板文件里');

                $form->radio('is_need_round', '是否变圆')->options(Schedule::IS_NEED_ROUND)->default(Schedule::IS_NEED_ROUND_OFF)
                    ->help("开启后，头像会从正方形，变成正圆。圆的直径以宽度为准。");

                $form->number('x','x轴位置')->required()->default(0)->help('头像展示在画板的X轴位置，坐标原点在画板左上角');
                $form->number('y','y轴位置')->required()->default(0)->help('头像展示在画板的Y轴位置，坐标原点在画板左上角');

                $form->number('width','头像的宽度和高度相同')->required()->default(0)->help('头像的大小，头像的宽度和高度相同');

                $form->number('fake_uid','用于预览的用户头像')->default(0)->help('请填写uid,用于预览的用户头像，不填的话使用默认用户');
                break;
            case Schedule::MODULE_TYPE_QR:
                $form->hidden('id','二维码模块id');
                $form->text('title','标题')->required()->default("")->help('请输入该模块的名称，用于标记这个模块是什么信息，会出现在模板文件里');

                $form->number('x','二维码的x轴位置')->required()->default(0)->help('二维码展示在画板的X轴位置，坐标原点在画板左上角');
                $form->number('y','二维码的y轴位置')->required()->default(0)->help('二维码展示在画板的Y轴位置，坐标原点在画板左上角');

                $form->number('width','二维码的宽度和高度相同')->required()->default(0)->help('二维码的大小,二维码的宽度和高度相同');

                $form->radio('is_hyaline', '是否透明')->options(Schedule::QR_DISPLAY_TYPE)->default(Schedule::QR_DISPLAY_HYALINE)
                    ->help("二维码的展示方式")
                    ->when(Schedule::QR_DISPLAY_NOT_HYALINE, function(Form $form) {
                        $form->color('background_color','二维码背景色')->default("#ffffff")->required()->help('图片展示在画板的X轴位置，坐标原点在画板左上角');
                        $form->number('margin','二维码的边框白条宽度')->required()->default(0)->help('总体的二维码大小不随这个值改变。二维码的边框白条宽度，单位是二维码数据单元的宽度');
                    });


                $form->text('fake_url','用于跳转的url')->default("")->help('用于二维码的跳转地址，不填的话使用默认地址');
                break;
            case Schedule::MODULE_TYPE_TEXT:
                $form->hidden('id','文本模块id');
                $form->text('title','标题')->required()->default("")->help('请输入该模块的名称，用于标记这个模块是什么信息，会出现在模板文件里');

                $form->radio('align_type', '对齐方式')->options(Schedule::ALIGN_TYPE)->default(Schedule::ALIGN_TYPE_LEFT)
                    ->help("文本的x轴计算方式<br/>1.左对齐：和其他模块计算方式一样，以模块的左边开始计算。<br/>2.居中：为了居中效果，所以模块的X轴以中间点开始计算。<br/>3.以模块的右边开始算。");

                $form->number('x','文字的x轴位置')->required()->default(0)->help('文字展示在画板的X轴位置，坐标原点在画板左上角');
                $form->number('y','文字的y轴位置')->required()->default(0)->help('文字展示在画板的Y轴位置，坐标原点在画板左上角');

                $form->number('size','文字的大小')->required()->default(0)->help('文字的大小');

                $form->select('font_family', '字体类型')->options(Schedule::FONT_FAMILY)->required();

                $form->color('color','字体颜色')->default("#000000")->required()->help('字体颜色');
                $form->number('max_width','文本的最大长度')->required()->default(100000)->help('文本的最大长度，文本的长度超过最大长度时，会进行换行');
                $form->number('line_margin','文本换行时的行间距')->required()->default(0)->help('文本换行时的行间距');

                $form->text('fake_text','用于预览的文本')->default("")->help('用于预览的文本，不填的话使用默认文本');
                break;
            case Schedule::MODULE_TYPE_ZIP_NAME :
                $form->hidden('id','zip包模块id');
                $form->text('title','标题')->required()->default("")->help("请输入该模块的名称，用于标记这个模块是什么信息，会出现在模板文件里<br/>模板中名字中不能填写带 ".Schedule::UNLEGAL_CHAR." 等特殊字符和表情！！！");
                break;
        }

        $functionName = Schedule::MODULE_ADD_FUNCTION_LIST[$moduleType];
        $form->action("/admin/ImageCreate/imageId/{$id}/moduleId/{$moduleId}/{$functionName}");
        return $form;
    }

    public function addImgModule(Request $request, $id, $moduleId)
    {
        $rs = $this->authControl($id);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '权限不够，只有创建者有权限编辑'
            ]);
            return back()->with(compact('error'))->withInput();
        }

        // 图片模块表里的id
        $imgModuleId = $request->input('id', 0);

        $saveData = array(
            "y" => $request->input('y', 0),
            "fake_url" => $request->input('fake_url', ""),
            "align_type" => $request->input('align_type', 0),
            "is_need_round" => $request->input('is_need_round', 0),
            "width" => $request->input('width', 0),
            "height" => $request->input('height', 0),
            "image_create_id" => $id,
            "i_status" => ImageCreateModuleImg::STATUS_NORMAL
        );

        // x轴坐标 居中时没有存在意义
        $xInput = $request->input('x', 0);
        if ($saveData["align_type"] != Schedule::ALIGN_TYPE_CENTER) {
            $saveData["x"] = $xInput;
        }

        // 更新
        $currentTime = time();
        if ($imgModuleId) {
            $saveData["edittime"] = $currentTime;
            $returnModuleImageId = ImageCreateModuleImg::saveInfo($imgModuleId, $saveData);
        } else {
            // 新增
            $saveData["addtime"] = $currentTime;
            $returnModuleImageId = ImageCreateModuleImg::addInfo($saveData);
        }

        if($returnModuleImageId) {
            // 模板 与 模块 表关联信息不存在 则添加
            if (!$moduleId) {
                $imageCreateModuleData = array(
                    "title" => $request->input('title', ""),
                    "image_create_id" => $id,
                    "i_status" => ImageCreateModule::STATUS_NORMAL,
                    "module_obj_id" => $returnModuleImageId,
                    "module_type" => Schedule::MODULE_TYPE_IMG,
                    "addtime" => $currentTime,
                    "sort" => $currentTime - 10000000
                );

                $imageCreateModuleId = ImageCreateModule::addInfo($imageCreateModuleData);

                if ($imageCreateModuleId) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            } else {
                $updateModuleInfo = array(
                    "title" => $request->input('title', ""),
                    "edittime" => $currentTime
                );

                $rs = ImageCreateModule::saveInfo($moduleId, $updateModuleInfo);

                if ($rs) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存模块关联信息失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            }

        } else {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function addAvatarModule(Request $request, $id, $moduleId)
    {
        $rs = $this->authControl($id);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '权限不够，只有创建者有权限编辑'
            ]);
            return back()->with(compact('error'))->withInput();
        }

        // 头像模块表里的id
        $avatarModuleId = $request->input('id', 0);

        $saveData = array(
            "is_need_round" => $request->input('is_need_round', 0),
            "x" => $request->input('x', 0),
            "y" => $request->input('y', 0),
            "fake_uid" => $request->input('fake_uid', 0),
            "width" => $request->input('width', 0),
            "image_create_id" => $id,
            "i_status" => ImageCreateModuleAvatar::STATUS_NORMAL
        );

        // 更新
        $currentTime = time();
        // 存在是修改
        if ($avatarModuleId) {
            $saveData["edittime"] = $currentTime;
            $returnModuleAvatarId = ImageCreateModuleAvatar::saveInfo($avatarModuleId, $saveData);
        } else {
            // 新增
            $saveData["addtime"] = $currentTime;
            $returnModuleAvatarId = ImageCreateModuleAvatar::addInfo($saveData);
        }

        if($returnModuleAvatarId) {
            // 模板 与 模块 表关联信息不存在 则添加
            if (!$moduleId) {
                $imageCreateModuleData = array(
                    "title" => $request->input('title', ""),
                    "image_create_id" => $id,
                    "i_status" => ImageCreateModule::STATUS_NORMAL,
                    "module_obj_id" => $returnModuleAvatarId,
                    "module_type" => Schedule::MODULE_TYPE_AVATAR,
                    "addtime" => $currentTime,
                    "sort" => $currentTime - 10000000
                );

                $imageCreateModuleId = ImageCreateModule::addInfo($imageCreateModuleData);

                if ($imageCreateModuleId) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            } else {
                $updateModuleInfo = array(
                    "title" => $request->input('title', ""),
                    "edittime" => $currentTime
                );

                $rs = ImageCreateModule::saveInfo($moduleId, $updateModuleInfo);

                if ($rs) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存模块关联信息失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            }
        } else {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function addQrModule(Request $request, $id, $moduleId)
    {
        $rs = $this->authControl($id);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '权限不够，只有创建者有权限编辑'
            ]);
            return back()->with(compact('error'))->withInput();
        }

        // 二维码模块表里的id
        $qrModuleId = $request->input('id', 0);

        $saveData = array(
            "x" => $request->input('x', 0),
            "y" => $request->input('y', 0),
            "fake_url" => $request->input('fake_url', ""),
            "width" => $request->input('width', 0),
            "margin" => $request->input('margin', 0),
            "is_hyaline" => $request->input('is_hyaline', 0),
            "background_color" => $request->input('background_color', "#ffffff"),
            "image_create_id" => $id,
            "i_status" => ImageCreateModuleQr::STATUS_NORMAL
        );

        // 更新
        $currentTime = time();
        if ($qrModuleId) {
            $saveData["edittime"] = $currentTime;
            $returnModuleImageId = ImageCreateModuleQr::saveInfo($qrModuleId, $saveData);
        } else {
            // 新增
            $saveData["addtime"] = $currentTime;
            $returnModuleImageId = ImageCreateModuleQr::addInfo($saveData);
        }

        if($returnModuleImageId) {
            // 模板 与 模块 表关联信息不存在 则添加
            if (!$moduleId) {
                $imageCreateModuleData = array(
                    "title" => $request->input('title', ""),
                    "image_create_id" => $id,
                    "i_status" => ImageCreateModule::STATUS_NORMAL,
                    "module_obj_id" => $returnModuleImageId,
                    "module_type" => Schedule::MODULE_TYPE_QR,
                    "addtime" => $currentTime,
                    "sort" => $currentTime - 10000000
                );

                $imageCreateModuleId = ImageCreateModule::addInfo($imageCreateModuleData);

                if ($imageCreateModuleId) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            } else {
                $updateModuleInfo = array(
                    "title" => $request->input('title', ""),
                    "edittime" => $currentTime
                );

                $rs = ImageCreateModule::saveInfo($moduleId, $updateModuleInfo);

                if ($rs) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存模块关联信息失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            }
        } else {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function addTextModule(Request $request, $id, $moduleId)
    {
        $rs = $this->authControl($id);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '权限不够，只有创建者有权限编辑'
            ]);
            return back()->with(compact('error'))->withInput();
        }

        // 文本模块表里的id
        $textModuleId = $request->input('id', 0);

        $saveData = array(
            "align_type" => $request->input('align_type', Schedule::ALIGN_TYPE_LEFT),
            "x" => $request->input('x', 0),
            "y" => $request->input('y', 0),
            "fake_text" => $request->input('fake_text', ""),
            "size" => $request->input('size', 0),
            "font_family" => $request->input('font_family', Schedule::FONT_FAMILY_SOURCEHANSANSSC_BOLD_INDEX),
            "color" => $request->input('color', ""),
            "max_width" => $request->input('max_width', 0),
            "image_create_id" => $id,
            "i_status" => ImageCreateModuleText::STATUS_NORMAL,
            "line_margin" => $request->input('line_margin', 0)
        );

        // 更新
        $currentTime = time();
        if ($textModuleId) {
            $saveData["edittime"] = $currentTime;
            $returnModuleImageId = ImageCreateModuleText::saveInfo($textModuleId, $saveData);
        } else {
            // 新增
            $saveData["addtime"] = $currentTime;
            $returnModuleImageId = ImageCreateModuleText::addInfo($saveData);
        }

        if($returnModuleImageId) {
            // 模板 与 模块 表关联信息不存在 则添加
            if (!$moduleId) {
                $imageCreateModuleData = array(
                    "title" => $request->input('title', ""),
                    "image_create_id" => $id,
                    "i_status" => ImageCreateModule::STATUS_NORMAL,
                    "module_obj_id" => $returnModuleImageId,
                    "module_type" => Schedule::MODULE_TYPE_TEXT,
                    "addtime" => $currentTime,
                    "sort" => $currentTime - 10000000
                );

                $imageCreateModuleId = ImageCreateModule::addInfo($imageCreateModuleData);

                if ($imageCreateModuleId) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            } else {
                $updateModuleInfo = array(
                    "title" => $request->input('title', ""),
                    "edittime" => $currentTime
                );

                $rs = ImageCreateModule::saveInfo($moduleId, $updateModuleInfo);

                if ($rs) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存模块关联信息失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            }
        } else {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function addZipNameModule(Request $request, $id, $moduleId)
    {
        $rs = $this->authControl($id);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '权限不够，只有创建者有权限编辑'
            ]);
            return back()->with(compact('error'))->withInput();
        }

        // Zip NAME 模块表里的id
        $zipModuleId = $request->input('id', 0);

        $saveData = array(
            "image_create_id" => $id,
            "i_status" => ImageCreateModuleZip::STATUS_NORMAL
        );

        // 更新
        $currentTime = time();
        if ($zipModuleId) {
            $saveData["edittime"] = $currentTime;
            $returnModuleZipId = ImageCreateModuleZip::saveInfo($zipModuleId, $saveData);
        } else {
            // 新增
            $saveData["addtime"] = $currentTime;
            $returnModuleZipId = ImageCreateModuleZip::addInfo($saveData);
        }

        if($returnModuleZipId) {
            // 模板 与 模块 表关联信息不存在 则添加
            if (!$moduleId) {
                $imageCreateModuleData = array(
                    "title" => $request->input('title', ""),
                    "image_create_id" => $id,
                    "i_status" => ImageCreateModule::STATUS_NORMAL,
                    "module_obj_id" => $returnModuleZipId,
                    "module_type" => Schedule::MODULE_TYPE_ZIP_NAME,
                    "addtime" => $currentTime,
                    "sort" => $currentTime - 10000000
                );

                $imageCreateModuleId = ImageCreateModule::addInfo($imageCreateModuleData);

                if ($imageCreateModuleId) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            } else {
                $updateModuleInfo = array(
                    "title" => $request->input('title', ""),
                    "edittime" => $currentTime
                );

                $rs = ImageCreateModule::saveInfo($moduleId, $updateModuleInfo);

                if ($rs) {
                    return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
                } else {
                    $error = new MessageBag([
                        'title' => '保存模块关联信息失败，请重试'
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            }

        } else {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public  function sort(Request $request, $id)
    {
        $rs = $this->authControl($id);
        if (!$rs) {
            return response()->json([
                'status' => false,
                'message' => "权限不够，只有创建者有权限编辑",
            ]);
        }

        $sortInfo = $request->input('sort');
        foreach ($sortInfo as $moduleId => $sort) {
            $saveData = array(
                "sort" => $sort
            );

            ImageCreateModule::saveInfo($moduleId, $saveData);
        }

        return redirect(url("/admin/ImageCreate/{$id}/edit/".Schedule::TEMPLATE_CONFIGURE_TAB_MODULE_LIST));
    }

    private function onlineScript()
    {
        return <<<SCRIPT
        $('.online-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要上架架该课程:'+id+'吗？')){
                let url = 'ImageCreate/onlineTemplate'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
        });
SCRIPT;
    }

    private function DeleteScript()
    {
        return <<<SCRIPT
        $('.offline-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var module = $(this).data('module');
            if(confirm('确定要删除该模块:'+id+'吗？')){
                let url = '/admin/ImageCreate/deleteModule'
                let params = {id:id,module:module}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            self.location.href = result.url;
                        }, 500);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
        });
SCRIPT;
    }

    // 权限控制 只有创建者 和 超级管理员能对内容进行编辑
    private function authControl($imageCreateId)
    {
        $adminId = Admin::user()->id;
        $accessName = Admin::user()->find($adminId)->name;

        $imageCreateData = ImageCreate::getDataById($imageCreateId);
        if ((isset($imageCreateData["admin_id"]) && $imageCreateData["admin_id"] == $adminId) || $accessName == "Administrator" || $accessName == "xuzhongjie") {
            return true;
        }

        return false;
    }
}